package com.ruoyi.web.controller.example;


import com.alibaba.fastjson2.JSON;
import com.ruoyi.ResLipstick.domain.ResLipstick;
import com.ruoyi.ResLipstick.service.ResLipstickService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;
@Anonymous
@Api(tags = "redis测试")
@RestController
@RequestMapping("/redis")
public class RedisController {  //董虹妤2619
    @Autowired
    ResLipstickService service;
    @Autowired
    RedisCache redis;
    @GetMapping("/testRedis")
    @ApiImplicitParam(name="name",value = "xingming",required = true ,dataType = "String" ,paramType = "query")
    @ApiOperation(value = "测试redis")
    public AjaxResult testRedis(@RequestParam String name){
        //想使用，就得先获取到redis对象
        redis.setCacheObject("myName",name,2000, TimeUnit.SECONDS);
        return AjaxResult.success("姓名存入redis成功");
    } //体会redis缓存作用
    @GetMapping("/GetLipstickByName")
    @ApiOperation(value = "redis作为缓存")
    public AjaxResult GetLipstickByName(String name) {
        //先查询redis，看看有没有数据，有数据直接返回，就不走下面代码了
        //1w人同时查询，只有一次查了数据库，9999次都查了redis
        String result = redis.getCacheObject(name);
        if (result != "" && result != null) {
            return AjaxResult.success("我是直接从redis获取的：" + result);
        }
        //如果上面没有返回，说明redis中没有查询到，那么就需要去mysql中再次查询
        //生成一个resshop对象，并赋值
        ResLipstick re = new ResLipstick();
        re.setName(name);
        List<ResLipstick> list = service.getLipstickList(re);
        String json = JSON.toJSONString(list);
        redis.setCacheObject(name, json);//这一步把mysql获取的数据存入到了redis里
        return AjaxResult.success(service.getLipstickList(re));
    }
}
